package frontend;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import logs.LogFactory;

import org.apache.log4j.Logger;

import backend.Course;
import backend.db.ORM;
import backend.exceptions.ElementNotFoundException;

/**
 * Servlet implementation class AvailableCourses
 */
public class AvailableCourses extends HttpServlet {
  private static final Logger logger = LogFactory.getLog(AvailableCourses.class);
  private static final long serialVersionUID = 1L;
  
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) {
    logger.debug("AvailableCourses");
    final String username = request.getParameter("username");
    final String course = request.getParameter("course");
    try {
      final Course c = ORM.getCourseByName(course);
      if (ORM.isCourseAvailable(username, c)) {
        logger.debug("course " + c.courseName + " is available for user " + username);
        ORM.addCourseToUser(username, course, c.groupNum);
      }
    } catch (final ElementNotFoundException e) {
      logger.warn("tried to add the non-existing course " + course + " to user " + username, e);
      try {
        response.sendError(HttpStatus.SC_BAD_REQUEST);
      } catch (final IOException e1) {
        logger.error("couldn't send error " + HttpStatus.SC_BAD_REQUEST, e1);
      }
    }
  }
}
